package com.cmwa.solution.utils;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

@SuppressWarnings("unchecked")
public class JsonUtil {
	private static ObjectMapper objectMapper = new ObjectMapper();
	
	public static <T>T parseObject(String res,Class<T> cls){
		JSONObject obj=JSONObject.fromObject(res);
		T t=(T)JSONObject.toBean(obj,cls);
		return t;
	}
	
	public static <T>List<T> parseListObject(String jsonString, Class<T> cls){
		List<T> yieldDtoList = new ArrayList<T>();
		JSONArray jsons = JSONArray.fromObject(jsonString);
		JSONObject jsonNode;
		for(Object o : jsons){
			jsonNode = JSONObject.fromObject(o);
			yieldDtoList.add((T)JSONObject.toBean(jsonNode, cls));
		}
		return yieldDtoList;
	}
	
	public static String toJson(Object obj) {
		String jsonStr = null;
		try {
			objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			jsonStr = objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonStr;
	}
	
	public static String toJson(Object obj, boolean serializationNull) {
		String jsonStr = null;
		try {
			objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			objectMapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
			jsonStr = objectMapper.writeValueAsString(obj);
			objectMapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_DEFAULT);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonStr;
	}
	
	public static <T>T parseJson(String json, Class<T> cls) {
		try {
			return objectMapper.readValue(json, cls);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
